package com.hbue.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbue.springboot.mapper.ManageWorkerMapper;
import com.hbue.springboot.mapper.TbAccountMapper;
import com.hbue.springboot.mapper.TbWorkerMapper;
import com.hbue.springboot.pojo.TbAccount;
import com.hbue.springboot.pojo.TbWorker;
import com.hbue.springboot.service.ManageWorkerService;
import com.hbue.springboot.service.TbWorkerService;
import com.hbue.springboot.utils.QueryParams;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Service
@Transactional
@RequiredArgsConstructor
public class ManageWorkerServiceImpl implements ManageWorkerService {
    private final ManageWorkerMapper manageWorkerMapper;
    private final TbAccountMapper tbAccountMapper;

    public List<TbWorker> getAllWorkers() {
        return manageWorkerMapper.selectList(new QueryWrapper<TbWorker>());
    }

    public int addWorker(TbWorker worker) {
        return manageWorkerMapper.insert(worker);
    }

    public int deleteWorker(int id) {
        return manageWorkerMapper.deleteById(id);
    }


    public int updateWorker(TbWorker worker) {
        return manageWorkerMapper.updateById(worker);
    }

    public List<TbWorker> getWorkerByName(String workerName) {
        return manageWorkerMapper.getWorkerByName(workerName);
    }

    public int updateWorkerSalary(int money, int id) {
        System.out.println(money);
        return manageWorkerMapper.updateWorkerSalaryById(money, id);
    }

    public int deleteWorkers(List<Integer> ids) {
        for (int i = 0; i < ids.size(); i++) {
            if (manageWorkerMapper.deleteById(ids.get(i)) == 0) return 0;
        }
        return 1;
    }

    public void uploadImage(MultipartFile file) {

    }

    public IPage<TbWorker> listWorker(QueryParams queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        IPage<TbWorker> page = new Page<>(pageNum , pageSize);
        return manageWorkerMapper.selectPage(page, null);
    }

    public int saveOrUpdate(TbWorker worker)
    {
        if (worker.getId() == null) {
            TbAccount account = new TbAccount();
            account.setUserName(worker.getWorkerName());
            account.setUserPwd(DigestUtils.md5DigestAsHex("admin".getBytes()));
            account.setUserRole(1);
            tbAccountMapper.insert(account);
            return manageWorkerMapper.insert(worker);
        }
        else return manageWorkerMapper.updateById(worker);
    }
}
